﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// Filter text regions
    /// </summary>
    public class PrintedTextRegion : BaseForeBackgroundColorFilter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PrintedTextRegion"/> class.
        /// </summary>
        public PrintedTextRegion()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="PrintedTextRegion"/> class.
        /// </summary>
        /// <param name="_printedTextRegion">The _printed text region.</param>
        internal PrintedTextRegion(PrintedTextRegion _printedTextRegion)
        { 
        }

        /// <summary>
        /// Execute this Filter
        /// A Debug Statement is written if a concrete Filter is called
        /// </summary>
        /// <param name="_bitmap"></param>
        /// <returns></returns>
        public override UnsafeBitmap Execute(UnsafeBitmap _bitmap)
        {
            UnsafeBitmap bitmap = _bitmap;

            int nHeight = bitmap.Height;
            int nWidth = bitmap.Width;

            UnsafeBitmap bitmapOpened = new Open().ExecuteCloned(_bitmap);
            UnsafeBitmap bitmapClosed = new Close().ExecuteCloned(_bitmap);

            int x = 0;
            int y = 0;
            for (y = 0; y < nHeight; y++)
            {
                for (x = 0; x < nWidth; x++)
                {
                    Color colorClosed = bitmapClosed.GetPixel(x, y);
                    Color colorOpen = bitmapOpened.GetPixel(x,y);
                    _bitmap.SetPixel(x, y, ColorFunctions.DistanceSquared(colorClosed, colorOpen) == 0 ? m_ColorForeground : m_ColorBackground);
                }
            }

            bitmapOpened.UnlockImage();
            bitmapClosed.UnlockImage();

            return _bitmap;
        }

        /// <summary>
        /// This is used to clone a filter, each filter must implement it's own clone functionality
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new PrintedTextRegion(this);
        }
    }
}
